package nciae.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import nciae.db.common.CommonResult;
import nciae.db.mapper.ExpertMapper;
import nciae.db.mapper.HomeworkDetailMapper;
import nciae.db.mapper.HomeworkMapper;
import nciae.db.mapper.StudentMapper;
import nciae.db.pojo.dto.ApiIsSubmitHomeWorkDTO;
import nciae.db.pojo.dto.FileTempDTO;
import nciae.db.pojo.entity.*;
import nciae.db.pojo.vo.HomeworkDetailVo;
import nciae.db.service.HomeworkDetailService;
import nciae.db.utils.FileUploadUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HomeworkDetailServiceImpl extends ServiceImpl<HomeworkDetailMapper, HomeworkDetail> implements HomeworkDetailService {


    @Autowired
    private HomeworkDetailMapper homeworkDetailMapper;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ExpertMapper expertMapper;


    @Override
    public CommonResult<List<HomeworkDetailVo>> search(Integer page, Integer size, String student, Integer select, String homeworkType, String expertName) {
        CommonResult<List<HomeworkDetailVo>> rs = new CommonResult<>();
        try {
            Page<HomeworkDetail> pg = new Page<>(page, size);
            QueryWrapper<HomeworkDetail> queryWrapper = new QueryWrapper<>();
            if (student != null && !student.isEmpty()) {
                QueryWrapper<Student> wrapper = new QueryWrapper<>();
                wrapper.eq("name", student); // 假设您想要根据学生姓名查询所有学生
                List<Student> students = studentMapper.selectList(wrapper); // 查询所有符合条件的学生
                if (!students.isEmpty()) {
                    // 假设您想要将学生ID添加到另一个查询的查询条件中
                    queryWrapper.in("student_id", students.stream().map(Student::getId).collect(Collectors.toList()));
                } else {
                    rs.setCode(404);
                    rs.setMsg("未找到该学生");
                    return rs;
                }
            }
            if (select != null) {
                queryWrapper.eq("is_read", select);
            }
            if (homeworkType != null && !homeworkType.isEmpty()) {
                QueryWrapper<Homework> wrapper = new QueryWrapper<>();
                wrapper.eq("homework_type", homeworkType);
                List<Homework> homeworkList = homeworkMapper.selectList(wrapper);
                // 如果作业列表不为空，提取作业ID并进行查询
                if (homeworkList != null && !homeworkList.isEmpty()) {
                    // 获取所有作业的ID
                    List<Integer> homeworkIds = homeworkList.stream()
                            .map(Homework::getId)  // 提取出每个作业的ID
                            .collect(Collectors.toList());
                    // 在查询作业详情时，使用in条件匹配多个作业ID
                    queryWrapper.in("homework_id", homeworkIds);
                } else {
                    // 如果没有找到作业类型对应的作业，可以选择返回空结果或其他处理
                    rs.setCode(404);
                    rs.setMsg("未找到对应的作业类型");
                    return rs;
                }
            }
            QueryWrapper<Expert> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", expertName); // 假设您想要根据学生姓名查询所有学生
            List<Expert> expert = expertMapper.selectList(wrapper); // 查询所有符合条件的学生
            if (!expert.isEmpty()) {
                // 假设您想要将学生ID添加到另一个查询的查询条件中
                queryWrapper.in("expert_id", expert.stream().map(Expert::getId).collect(Collectors.toList()));
            } else {
                rs.setCode(404);
                rs.setMsg("未找到该专家");
                return rs;
            }
            homeworkDetailMapper.selectPage(pg, queryWrapper);
            List<HomeworkDetail> list = pg.getRecords();
            List<HomeworkDetailVo> listVO = getHomeworkVOs(list);
            long count = pg.getTotal();
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setCount(count);
            rs.setData(listVO);
            return rs;
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误" + e.getMessage());
            return rs;
        }
    }

    private List<HomeworkDetailVo> getHomeworkVOs(List<HomeworkDetail> list) {
        ArrayList<HomeworkDetailVo> homeworkDetailVos = new ArrayList<>();
        for (HomeworkDetail s : list) {
            homeworkDetailVos.add(getHomeworkDetailVO(s));
        }
        return homeworkDetailVos;
    }

    private HomeworkDetailVo getHomeworkDetailVO(HomeworkDetail homeworkDetail) {
        HomeworkDetailVo homeworkDetailVo = new HomeworkDetailVo();
        BeanUtils.copyProperties(homeworkDetail, homeworkDetailVo);
        //设置作业对应的作业要求
        Integer homeworkId = homeworkDetail.getHomeworkId();
        Homework homework = homeworkMapper.selectById(homeworkId);
        homeworkDetailVo.setHomework(homework);
        //设置学员对应的姓名
        Integer studentId = homeworkDetail.getStudentId();
        Student student = studentMapper.selectById(studentId);
        homeworkDetailVo.setStudent(student);
        return homeworkDetailVo;
    }

    @Override
    public HomeworkDetailVo getHomeworkDetail(Integer id) {
        HomeworkDetailVo homeworkDetailVo = new HomeworkDetailVo();
        HomeworkDetail homeworkDetail;
        homeworkDetail = homeworkDetailMapper.selectById(id);
        Homework homework;
        homework = homeworkMapper.selectById(homeworkDetail.getHomeworkId());
        Student student;
        student = studentMapper.selectById(homeworkDetail.getStudentId());
        BeanUtils.copyProperties(homeworkDetail, homeworkDetailVo);
        homeworkDetailVo.setHomework(homework);
        homeworkDetailVo.setStudent(student);
        homeworkDetailVo.setFileNames(getHomeWorkDetailFileNames(homeworkDetail, homeworkDetail.getStudentId(), homeworkDetail.getHomeworkId()));
        homeworkDetailVo.setImageNames(getHomeWorkDetailImagesFileNames(homeworkDetail, homeworkDetail.getStudentId(), homeworkDetail.getHomeworkId()));

        return homeworkDetailVo;
    }

    private List<String> getHomeWorkDetailImagesFileNames(HomeworkDetail homeworkDetail, Integer StudentId, Integer HomeWorkId) {
        String urlImg = homeworkDetail.getUrlImg();
        return getImagesFileNames(urlImg, StudentId, HomeWorkId);
    }

    private List<String> getImagesFileNames(String urlImg, Integer StudentId, Integer HomeWorkId) {
        List<String> fileNames = new ArrayList<>();
        // 指定要查询的路径
        String path = urlImg;
        if (path == null) {
            return fileNames;
        }
        File directory = new File(path);

        // 检查路径是否存在且为目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录下的所有文件和文件夹
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 打印文件名
                    fileNames.add(FileUploadUtils.FILE_URL + "homeWorkFiles/" + String.valueOf(StudentId) + "/" + String.valueOf(HomeWorkId) + "/" + "img/" + file.getName());
                }
            }
        }
        return fileNames;
    }

    private List<String> getHomeWorkDetailFileNames(HomeworkDetail homeworkDetail, Integer StudentId, Integer HomeWorkId) {
        String urlFile = homeworkDetail.getUrlFile();
        return getFileNames(urlFile, StudentId, HomeWorkId);
    }

    private List<String> getFileNames(String url_file, Integer StudentId, Integer HomeWorkId) {
        List<String> fileNames = new ArrayList<>();
        // 指定要查询的路径
        String path = url_file;
        if (path == null) {
            return fileNames;
        }
        File directory = new File(path);

        // 检查路径是否存在且为目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录下的所有文件和文件夹
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 打印文件名
                    fileNames.add(FileUploadUtils.FILE_URL + "homeWorkFiles/" + String.valueOf(StudentId) + "/" + String.valueOf(HomeWorkId) + "/" + "file/" + file.getName());
                }
            }
        }
        return fileNames;
    }

    @Override
    public CommonResult<String> homeworkDetailSave(HomeworkDetailVo homeworkDetailVo) {
        CommonResult<String> rs = new CommonResult<>();
        try {
            Integer homeworkId = homeworkDetailVo.getHomeworkId();
            Homework homework = homeworkMapper.selectById(homeworkId);
            if (homework == null) {
                rs.setCode(-1);
                rs.setMsg("未找到对应的作业信息");
                return rs;
            }

            Integer id = homeworkDetailVo.getId();
            HomeworkDetail homeworkDetail = homeworkDetailMapper.selectById(id);
            if (homeworkDetail == null) {
                rs.setCode(-1);
                rs.setMsg("未找到对应的作业详情信息");
                return rs;
            }

            Integer score = homeworkDetailVo.getScore();
            String comment = homeworkDetailVo.getComment();
            if (homeworkDetail.getIsRead() == 0) {
                // 更新作业的批阅数量


                homework.setOverNum(homework.getOverNum() + 1); // 批阅数量加一
                int homeworkUpdateCount = homeworkMapper.updateById(homework);
                if (homeworkUpdateCount > 0) {
                    // 更新成功
                    rs.setCode(0);
                    rs.setMsg("更新作业信息成功");
                } else {
                    // 更新失败
                    rs.setCode(-1);
                    rs.setMsg("更新作业信息失败");
                }
                homeworkDetail.setIsRead(1);
            }
            // 更新作业详情
            homeworkDetail.setScore(score);
            homeworkDetail.setComment(comment);
            homeworkDetail.setReadDate(homeworkDetailVo.getReadDate());

            // 保存更新后的作业详情实体到数据库
            int updateCount = homeworkDetailMapper.updateById(homeworkDetail);
            if (updateCount > 0) {
                rs.setCode(0);
                rs.setMsg("批阅成功");
            } else {
                rs.setCode(-1);
                rs.setMsg("保存作业详情失败");
            }
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误：" + e.getMessage());
        }
        return rs;
    }

    @Override
    public CommonResult<Boolean> apiIsSubmitHomeWork(ApiIsSubmitHomeWorkDTO apiIsSubmitHomeWorkDTO) {
        CommonResult<Boolean> result = new CommonResult<>();
        try {
            Long homeWorkId = apiIsSubmitHomeWorkDTO.getHomeWorkId();
            Long studentId = apiIsSubmitHomeWorkDTO.getStudentId();
            if (homeWorkId == null || studentId == null) {
                result.setCode(-1);
                result.setMsg("参数错误");
            }
            QueryWrapper<HomeworkDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("homework_id", homeWorkId).eq("student_id", studentId);
            HomeworkDetail homeworkDetail = homeworkDetailMapper.selectOne(wrapper);
            if (homeworkDetail == null) {
                result.setCode(0);
                result.setMsg("未作答");
                result.setData(false);
            } else {
                result.setData(true);
                result.setCode(0);
                result.setMsg("查询成功");
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("发生错误: " + e.getMessage());
        }
        return result;
    }

    @Override
    public CommonResult<String> UploadHomeWorkFiles(MultipartFile file, Long studentId, Long homeWorkId) {
        CommonResult<String> Fileresult = FileUploadUtils.uploadHomeWorkFiles(file, studentId, homeWorkId);
        System.out.println(Fileresult);
        if (Fileresult.getCode() != 200) {
            return Fileresult;
        }

        // 获取上传的文件的磁盘路径
        String deskPath = Fileresult.getData();

        Path path = Paths.get(deskPath);

        System.out.println(deskPath);

        // 获取文件名
        String fileName = path.getFileName().toString();
        System.out.println(fileName);
        // 获取路径（不包含文件名）
        String filePath = path.getParent().toString();

        // 获取文件的文件名和前端加载路径
        String loadPathOrFileName ;

        CommonResult<String> result = new CommonResult<>();
        QueryWrapper<HomeworkDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("homework_id", homeWorkId).eq("student_id", studentId);
        HomeworkDetail homeworkDetail = homeworkDetailMapper.selectOne(wrapper);
        // 只提交了文件
        HomeworkDetail homeWorkDetail = new HomeworkDetail();  //家庭作业细节的信息
        homeWorkDetail.setHomeworkId(homeWorkId.intValue());
        homeWorkDetail.setStudentId(studentId.intValue());
        // 创建一个 Timestamp 对象表示当前时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        // 调用 setSubmitDate 方法，将 Timestamp 对象传递给它
        homeWorkDetail.setSubmitDate(timestamp);
        homeWorkDetail.setIsRead(0);


        Student student = studentMapper.selectById(studentId);
        Integer expertId = student.getExpertId();
        homeWorkDetail.setExpertId(expertId);
        //如果是图片文件
        if (Objects.requireNonNull(file.getContentType()).startsWith("image/")) {
            homeWorkDetail.setUrlImg(filePath);
            loadPathOrFileName =FileUploadUtils.FILE_URL + "homeWorkFiles" + "/" + studentId + "/" + homeWorkId + "/" + "img" + "/" + fileName;
            System.out.println(loadPathOrFileName);
        } else {
            homeWorkDetail.setUrlFile(filePath);
            System.out.println(fileName);
            loadPathOrFileName = fileName;
        }
        Homework homework = homeworkMapper.selectById(homeWorkId);
//      加一个判断查看是否是新提交的还是修改的
        HomeworkDetail homeworkDe = homeworkDetailMapper.selectOne(new QueryWrapper<HomeworkDetail>().eq("homework_id", homeWorkId).eq("student_id", studentId));
        int byId, i;
        if (homeworkDe == null) {
            homework.setSubmitNum(homework.getSubmitNum() + 1);
            byId = homeworkMapper.updateById(homework);
            i = homeworkDetailMapper.insert(homeWorkDetail);
        } else {
            homework.setSubmitNum(homework.getSubmitNum());
            byId = homeworkMapper.updateById(homework);
            i = homeworkDetailMapper.update(homeWorkDetail, new QueryWrapper<HomeworkDetail>().eq("id", homeworkDe.getId()));
        }
        System.out.println(i + ' ' + byId);
        if (i > 0 && byId > 0) {
            result.setCode(200);
            result.setMsg("上传成功");
            // 返回文件的访问路径
            System.out.println(loadPathOrFileName);
            result.setData(loadPathOrFileName);
        } else {
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
            return result;
        }
        return result;
    }

    @Override
    public ResponseEntity<Resource> downloadFiles(Integer id) {
        HomeworkDetail homeworkDetail = homeworkDetailMapper.selectById(id);
        Integer studentId = homeworkDetail.getStudentId();
        Student student = studentMapper.selectById(studentId);
        String tel = student.getTel();
        String name = student.getName();
        String urlFile = homeworkDetail.getUrlFile();
        return FileUploadUtils.downloadAllFiles(urlFile, tel + name);
    }
}